<template>
  <a-modal
      title="添加意向客户"
      :visible="visible"
      :destroyOnClose="true"
      :width="1000"
      :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
      @cancel="onClose"
      centered
  >
    <a-form layout="vertical">
      <a-row :wrap="true" :gutter="12">
        <div class="text-title">基础信息</div>
        <a-col :span="6">
          <a-form-item label="客户类型" v-bind="validateInfos.type">
            <a-select
                v-model:value="formData.type"
                style="width: 100%"
                placeholder="请选择客户类型"
                :options="typeOptions"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input
                v-model:value="formData.name"
                placeholder="请填写客户姓名"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="手机号码" v-bind="validateInfos.tel">
            <a-input
                v-model:value="formData.tel"
                placeholder="请输入手机号码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="公司" v-bind="validateInfos.company">
            <a-input
                v-model:value="formData.company"
                placeholder="请输入公司"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="行业" v-bind="validateInfos.industry">
            <a-select
                v-model:value="formData.industry"
                :options="industryOptions"
                placeholder="请填选择行业"
            >
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu"/>
                <a-divider style="margin: 4px 0"/>
                <div
                    style="
                          padding: 4px 8px;
                          cursor: pointer;
                          color: #1890ff;
                          text-align: center;
                        "
                    @mousedown="(e) => e.preventDefault()"
                    @click="addTag"
                >
                  添加
                </div>
              </template>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" v-if="formData.type == 2">
          <a-form-item label="选择品牌">
            <a-input v-model:value="brandData.brand_name" readonly placeholder="请选择品牌">
              <template #addonAfter>
                <a-button type="text" @click="selectBrandClick" size="small" style="height: 30px;">
                  <diff-filled/>
                </a-button>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="意向项目" v-bind="validateInfos.build_ids">
            <a-cascader
                v-model:value="formData.build_ids"
                :options="optionsBuild"
                placeholder="请选择"
                @change="buildChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="formData.type == 2 ? 6 :  12">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea
                placeholder="请输入"
                :auto-size="{ minRows: 1 }"
                v-model:value="formData.remark"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <div class="text-title">需求信息</div>
        </a-col>
        <a-col :span="6">
          <a-form-item label="需求面积段" v-bind="validateInfos.expect_area_max">
            <a-input-group size="default">
              <a-row :gutter="24">
                <a-col :span="10">
                  <a-input-number
                      v-model:value="formData.expect_area_min"
                      :min="0"
                      style="width: 100%;"
                  />
                </a-col
                >
                -
                <a-col :span="13">
                  <a-input-number
                      v-model:value="formData.expect_area_max"
                      addon-after="m²"
                      :min="0"
                      style="width: 100%;"

                  />
                </a-col>
              </a-row>
            </a-input-group>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="客户预算" v-bind="validateInfos.budget_amount">
            <a-input-number v-model:value="formData.budget_amount" addon-after="元"
                            style="width: 100%" :min="0" :precision="2"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="预计签约时间" v-bind="validateInfos.expect_contract">
            <a-date-picker
                class="w-100p"
                v-model:value="formData.expect_contract"
                valueFormat="YYYY-MM-DD"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="isAdmin">
          <div class="text-title">跟进人员</div>
        </a-col>
        <a-col :span="12" v-if="isAdmin">
          <a-form-item label="跟进人员">
            <a-radio-group v-model:value="formData.operate_type" size="small">
              <a-radio :value="1"
              ><span style="font-size: 12px">指定人员</span></a-radio
              >
              <a-radio :value="3"
              ><span style="font-size: 12px">加入公海</span></a-radio
              >
              <a-radio :value="4"
              ><span style="font-size: 12px">分配给创建人</span></a-radio
              >
            </a-radio-group>
            <template v-if="formData.operate_type == 1" class="m-t-10">

              <a-cascader
                  style="margin-top: 10px"
                  v-model:value="formData.followup_uid"
                  :options="groupOptions"
                  :load-data="getTeamList"
                  placeholder="请选择指定人员"
              />

            </template>
          </a-form-item>
        </a-col>

      </a-row>
    </a-form>

    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose"> 取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit"> 提交</a-button>
      </a-space>
    </div>

    <!-- 行业分类 -->
    <EditTag
        @closeTag="editTagClose"
        @success="editSuccess"
        :visible="editVisible"
    ></EditTag>

    <!-- 选择品牌 -->
    <SelectBrandModal
        :visible="visibleSelectBrand"
        :brandId="brandData?.id"
        @costConfirm="costConfirm"
        @close="visibleSelectBrand = false"
    />
  </a-modal>
</template>
<script>
import {defineComponent, reactive, toRefs, computed, watch, createVNode, ref} from "vue";
import {Form, message, Modal} from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import BLCOMMON, {TextTip} from "bl-common-vue3";
import {ExclamationCircleOutlined, DiffFilled} from "@ant-design/icons-vue";
import {useRouter} from "vue-router";
import EditTag from "@/views/village/BusinessManage/modules/EditTag.vue";
import SelectBrandModal from "./SelectBrandModal.vue"

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "AddCustomer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    EditTag,
    TextTip,
    VNodes: (_, {attrs}) => {
      return attrs.vnodes;
    },
    SelectBrandModal,
    DiffFilled
  },
  setup(props, {emit}) {
    const $router = useRouter();
    const state = reactive({
      userList: [],
      channelObject: {},
      channelList: [],
      industryOptions: [],
      editVisible: false,
      typeOptions: [],
      visibleSelectBrand: false,
      brandData: {},
      isAdmin: false,
    });

    const formData = reactive({
      name: '',
      tel: '',
      company: '',
      village_id: undefined,
      budget_amount: undefined, // 客户预算金额
      expect_contract: undefined, // 预计签约时间
      expect_area_min: undefined,
      expect_area_max: undefined,
      remark: '', // 备注
      operate_type: 0,
      followup_uid: undefined,
      industry: undefined,
      build_ids: [],
      build_id: undefined,
      type: undefined,
      brand_id: undefined
    });
    const ruleRef = reactive({
      name: [{required: true, message: "必填"}],
      tel: [{required: true, message: "必填"}],
      village_id: [{required: true, message: "必选"}],
      build_ids: [
        {
          required: true,
          message: "必选",
        },
      ],
      type: [
        {
          required: true,
          message: "必选",
        }
      ]
    });

    const {resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    const groupOptions = ref([]);
    const getGroupList = () => {
      request.post("/org", "/business/customerTeam/list").then(res => {
        // console.log(res)
        groupOptions.value = res.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            isLeaf: false,
          }
        })
      })
    }

    const getTeamList = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      // console.log(targetOption)
      request.get("/org", "/business/customerTeam/teamUserIndex", {team_id: targetOption.value}).then(res => {
        console.log(res)
        targetOption.loading = false;
        targetOption.children = [];
        targetOption.children = res.data.map(item => {
          return {
            label: item.name,
            value: item.uid
          }
        })
        groupOptions.value = [...groupOptions.value];
      });
    }

    // 意向楼宇
    const optionsBuild = ref([]);
    const getSelectVillage = () => {
      return new Promise(resolve => {
        request.get("/org", "/business/customerTeam/getSelectVillage").then(res => {
          resolve(res.data)
        })
      })
    }

    const getBuildList = () => {
      getSelectVillage().then(ids => {
        request
            .get("/org", "/build/villageAndBuildList/v2", {checked: 1})
            .then((res) => {
              let vList = [];
              res.villageList.forEach((item) => {
                if (ids.includes(item.id)) {
                  vList.push({
                    label: item.name,
                    value: item.id,
                    children: item.buildList.map((childItem) => {
                      return {
                        label: childItem.build_name,
                        value: childItem.id,
                      };
                    }),
                  });
                }
              });
              optionsBuild.value = vList;
            });
      })
    }

    //1招商领导 2招商专员
    const getRole = () => {
      request
          .get("/org", "/business/customerTeam/UserRoleInfo", {village_id: formData.village_id})
          .then((res) => {
            let level = store.getters.userInfo.level;
            if (res.role == 1 || level == 99) {
              state.isAdmin = true;
            } else {
              state.isAdmin = false;
            }
            if (state.isAdmin) {
              getGroupList();
              formData.operate_type = 1;
            }
          });
    };


    const getChannelList = () => {
      const key = "channel" + formData.village_id;
      if (formData.village_id) {
        if (Object.keys(state.channelObject).includes(key)) {
          state.channelList = state.channelObject[key];
        } else {
          request
              .get("/org", "/business/customer/channel/index", {
                village_id: formData.village_id,
              })
              .then((res) => {
                const list = res.list.map((item) => {
                  return {
                    value: item.id,
                    label: item.name,
                  };
                });
                state.channelList = list;
                state.channelObject[key] = list;
              });
        }
      } else {
        state.channelList = [];
      }
    };

    const onSubmit = () => {
      validate().then(() => {
        if (formData.operate_type == 1 && !formData.followup_uid) {
          message.warning('请选择指定人员');
          return;
        }
        let params = {};
        for (let key in formData) {
          if (formData[key] || formData[key] === 0) {
            params[key] = formData[key];
          }
        }
        if (params.build_ids?.length > 0) {
          params.village_id = params.build_ids[0];
          params.build_id =
              params.build_ids.length > 1 ? params.build_ids[1] : undefined;
        }
        if (formData.operate_type == 1 && formData?.followup_uid.length > 1) {
          params.followup_uid = formData?.followup_uid[1];
        }
        delete params.build_ids;
        request.post("/org", "/business/customer", params).then((res) => {
          message.success(res.msg || "添加成功!");
          emit("success");
        });
      });
    };


    const onClose = () => {
      emit("cancelAdd");
    };

    const industryList = () => {
      request.get("/org", "/manage/taglib/industry/all").then((res) => {
        if (res.list.length) {
          state.industryOptions = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              id: item.id,
            };
          });
        } else {
          Modal.confirm({
            title: () => "提示",
            content: () => "您需要先添加行业分类才能继续添加客户",
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            okText: () => "前往",
            onOk() {
              $router.push({
                name: "taglibIndustry",
              });
              onClose();
            },
            onCancel() {
              onClose();
            },
          });
        }
      });
    };

    const addTag = () => {
      state.editVisible = true;
    };
    const editTagClose = () => {
      state.editVisible = false;
    };
    const editSuccess = () => {
      editTagClose();
      industryList();
    };


    // 字典
    const getDictList = () => {
      request
          .get("/org", "/system/dict/data", {dict_menu_alias: "orgCustomerType"})
          .then((res) => {
            state.typeOptions = res.list.filter(
                (item) => item.dict_type == "org_custom_type"
            );
            if (state.typeOptions.length == 1) {
              formData.type = state.typeOptions[0].value
            }
          });
    };

    const isCategoryEdit = computed(() => {
      return BLCOMMON.utils.getBtnPermission([
        "customerBrandCategory",
        "curd",
        "list",
      ]);
    });

    // 选择品牌
    const selectBrandClick = () => {
      if (!isCategoryEdit.value) {
        message.warn('暂无权限')
        return
      }
      state.visibleSelectBrand = true
    }

    const costConfirm = (data) => {
      if (data.id) {
        state.brandData = data
        formData.brand_id = data.id
      } else {
        formData.brand_id = undefined
        state.brandData = {}

      }
      state.visibleSelectBrand = false
    }

    const init = () => {
      getDictList()
      getBuildList();
      industryList();
    };

    const buildChange = (value) => {
      state.isAdmin = false
      if (value?.length > 0) {
        formData.village_id = value[0];
        getRole()
      }
      getChannelList();
    };

    const reset = () => {
      state.userList = [];
      state.channelObject = {};
      state.channelList = [];
      state.industryOptions = [];
      optionsBuild.value = [];
      state.brandData = {}
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            reset();
          }
        }
    );

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      optionsBuild,
      onClose,
      onSubmit,
      getChannelList,
      addTag,
      editSuccess,
      editTagClose,
      buildChange,
      getTeamList,
      groupOptions,

      selectBrandClick,
      costConfirm
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-input-wrapper .ant-input-group-addon) {
  padding: 0;
}
</style>
